package com.epalmpay.service.yunstream.impl;

import com.epalmpay.dto.yunliu.UserAuthMessage;
import com.epalmpay.entity.Group;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.MemberGrade;
import com.epalmpay.entity.Userbase;
import com.epalmpay.entity.Wallet;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.MemberGradeMapper;
import com.epalmpay.mapper.MemberMapper;
import com.epalmpay.mapper.UserbaseMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.PayBalanceQuery;
import com.epalmpay.payplat.PayUpdatePayPwd;
import com.epalmpay.payplat.PayUserAccounts;
import com.epalmpay.payplat.result.PayBalanceResult;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.weixin.ITokenService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.yunstream.IYlLoginService;
import com.epalmpay.util.*;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by wucongpeng on 2017/8/7.
 */
@Service("YlLoginService")
public class YlLoginServiceImpl implements IYlLoginService {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private MemberGradeMapper memberGradeMapper;

    @Resource
    private UserbaseMapper userbaseMapper;
    
    @Autowired
	private ITokenService tokenService;
    
    @Resource
	private IWalletService walletService;

    @Override
    public Response updatecheckMemberInfo(String payGroupCode, UserAuthMessage userAuthMessage) throws Exception{
        Response message = new Response();
        //判断是否注册钱包,这里将云流后台返回的userId当成微信的OpenId去查询会员信息
        Member member = memberMapper.selectYlUserId(userAuthMessage.getUserId()); //查询用户信息
        if (member == null) {
            logger.info(String.format("用户还未注册支付钱包,OpenId:%s", userAuthMessage.getUserId()));
            //注册会员根据钱包大机构号查询大商户ID
            Group group = groupMapper.selectGroupByPayCode(payGroupCode);
            if (group == null) {
                return message.format(false, -1, "没有大商户信息", null);
            }
            //会员等级
   //         MemberGrade memberGrade = memberGradeMapper.selectMemberGradeByGroupIdAndGradeName(group.getId(), BizEnum.MemberGradeDefault.unattention.getName());
            
            List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(group.getId());
           // 取第二个会员等级
            MemberGrade memberGrade=memberGradeList.get(1);
            
            //如该手机号码pos机   包括已存在老用户已开户，账户合并处理   
        	Member memberPost=memberMapper.selectByPrimaryPhone(group.getId(), userAuthMessage.getPhoneNum(),BizEnum.MemberDevelopeMode.PosConsume.getType()); 
        	if(memberPost!=null){
        		//账户合并 
        		MemberMerge(memberGrade, userAuthMessage, payGroupCode, group.getId(),memberPost);
        	}else{
	        		 //用户信息组装
	                Userbase userbase = new Userbase();
	                userbase.setStatus(BizEnum.UserStatus.Normal.getType());
	                userbase.setUserType(CommonEnum.UserType.User.getType());
	                userbase.setGmtCreate(new Date());
	                userbase.setGmtModified(new Date());
	                userbase.setGroupId(group.getId());
	                userbase.setUsername(userAuthMessage.getPhoneNum());
	                //插入用户表
	                int i = userbaseMapper.insertSelective(userbase);
	                if (i == 1) {
	                	MemberAccounts(userbase.getId(), memberGrade, userAuthMessage, payGroupCode, group.getId());
	                }
        	}
        } else {
	            //根据钱包大机构号查询大商户ID
	            Group group = groupMapper.selectGroupByPayCode(payGroupCode);
	            if (group == null || member == null) {
	                return message.format(false, 0, "非法操作", null);
	            }
	            //查询余额
//	            PayBalanceQuery payBalanceQuery = PayBalanceQuery.initialize(member.getVirtualCard(), payGroupCode, UtilFun.createRandomNum(10),
//	                    DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createOrderNum());
//	            PayBalanceResult payBalanceResult = IPayAPI.accountBalanceQuery(payBalanceQuery, false);
	            
	            
	            Wallet wallet=walletService.selectwallet(member.getVirtualCard(), payGroupCode, member.getUserId());
	            
	            if (wallet == null) {
	                return message.format(false, 0, "余额查询失败", null);
	            }else {
	            	
	            	
	            	/**
	                 * 余额查询成功
	                 */
	                String balancequeryAddamt = wallet.getCanBalance()+"";
	                String balancequeryAddamtB = wallet.getNocanBalance()+"";
	                String memberBalance = String.format("%.2f", Double.valueOf(balancequeryAddamt) / 100);//A卡金额
	                String memberBalanceB = String.format("%.2f", Double.valueOf(balancequeryAddamtB) / 100);//B卡金额
	                try {
	                    String payPwd = UtilFun.creatDefaultPayPwd(userAuthMessage.getPhoneNum());
	                    String oldPwd = member.getTradePassword();
	                    
	                    if (oldPwd.equals(AES.AESEncode(Const.AceKey, payPwd))) {
	                        member.setNeedResetPwd(Byte.valueOf("1"));
	                    } else {
	                        member.setNeedResetPwd(Byte.valueOf("0"));
	                    }
	                    member.setMemberBalance(Double.parseDouble(memberBalance));
	                    member.setMemberBalanceB(Double.parseDouble(memberBalanceB));
	                } catch (Exception e) {
	                    // TODO Auto-generated catch block
	                    e.printStackTrace();
	                }
	                Token token=tokenService.getTokenInfo(member.getId()+"");
	                return message.format(true, 0, "成功", member,token.getValue());
	            	
	            }
        }
        return null;
    }
    
    
    
    /**
     * 账户信息修改
     * @param
     * @param memberGrade
     * @param userAuthMessage
     * @param payGroupCode
     * @param groupId
     * @return
     */
    public Response MemberMerge (MemberGrade memberGrade,UserAuthMessage userAuthMessage,String payGroupCode,Long groupId,Member memberPost){
    	Response message = new Response();
    	//组装会员信息
    	memberPost.setGroupId(groupId);
    	memberPost.setPhone(userAuthMessage.getPhoneNum());
        if (StringUtils.isNotBlank(userAuthMessage.getUserName())) {
        	memberPost.setName(userAuthMessage.getUserName());
        } else {
        	memberPost.setName("云流客户");
        }
        memberPost.setThirdUserId(userAuthMessage.getUserId());
        memberPost.setPicture(userAuthMessage.getImgPath());
        memberPost.setStatus(BizEnum.MemberStatus.unattention.getType());
//        memberPost.setGmtCreate(new Date());
        memberPost.setGmtModified(new Date());
        memberPost.setWalletGmtCreate(new Date());
        memberPost.setWalletStatus(1);
        memberPost.setWxsubStaus(0);
        memberPost.setApproveStatus(0);
        if (memberGrade != null) {
        	memberPost.setGradeId(memberGrade.getId());
        }
        /**
         * 判断支付密码格试是否合法
         */
        String memberPayPwd = null;
        if (userAuthMessage.getPhoneNum().length() < 6) {
            return message.format(false, 99, "资料信息不全请注册", null);
        } else {
            memberPayPwd = UtilFun.creatDefaultPayPwd(userAuthMessage.getPhoneNum());
        }
        memberPost.setTradePassword(AES.AESEncode(Const.AceKey, memberPayPwd));
        //会员卡号生成
        memberPost.setCardNo(DateUtil.getMonth() + Tools.getRandomNum(6));
        try {
            //防止随便输入身份证号
            if (userAuthMessage.getIdNumber() != null && userAuthMessage.getIdNumber().length() == 18) {
                Integer sex = Integer.valueOf(userAuthMessage.getIdNumber().substring(16, 17));
                Byte memberSex = Byte.valueOf(Integer.valueOf(sex.intValue() % 2).toString());
                memberPost.setSex(Integer.valueOf(memberSex));
                memberPost.setIdNo(userAuthMessage.getIdNumber());
            } else {
                return message.format(false, -1, "身份证格式不正确", null);
            }
        } catch (Exception e) {
            return message.format(false, -1, "身份证格式不正确", null);
        }
        //插入会员表
       // member1.setUserId(userId);
        int j = memberMapper.updateByPrimaryKeySelective(memberPost);
        if (j != 1) {
        	 return message.format(false, -1, "会员信息更新异常", null);
        }
        Token token=tokenService.getTokenInfo(memberPost.getId()+"");
        memberPost.setMemberBalance(0.00);
        memberPost.setMemberBalanceB(0.00);
        memberPost.setNeedResetPwd(Byte.valueOf("1"));
        return message.format(true, Integer.parseInt(memberPost.getId() + ""), "成功", memberPost,token.getValue());
    }
    
    /**
     * 会员开户
     * @param userId
     * @param memberGrade
     * @param userAuthMessage
     * @param payGroupCode
     * @param groupId
     * @return
     */
    public Response MemberAccounts (Long userId,MemberGrade memberGrade,UserAuthMessage userAuthMessage,String payGroupCode,Long groupId){
    	Response message = new Response();
    	//组装会员信息
        Member member1 = new Member();
        member1.setGroupId(groupId);
        member1.setPhone(userAuthMessage.getPhoneNum());
        if (StringUtils.isNotBlank(userAuthMessage.getUserName())) {
            member1.setName(userAuthMessage.getUserName());
        } else {
            member1.setName("云流客户");
        }
        member1.setThirdUserId(userAuthMessage.getUserId());
        member1.setPicture(userAuthMessage.getImgPath());
        member1.setStatus(BizEnum.MemberStatus.unattention.getType());
        member1.setGmtCreate(new Date());
        member1.setGmtModified(new Date());
        member1.setWalletGmtCreate(new Date());
        member1.setWalletStatus(1);
        member1.setWxsubStaus(0);
        member1.setApproveStatus(0);
        if (memberGrade != null) {
            member1.setGradeId(memberGrade.getId());
        }
        /**
         * 判断支付密码格试是否合法
         */
        String memberPayPwd = null;
        if (userAuthMessage.getPhoneNum().length() < 6) {
            return message.format(false, 99, "资料信息不全请注册", null);
        } else {
            memberPayPwd = UtilFun.creatDefaultPayPwd(userAuthMessage.getPhoneNum());
        }
        member1.setTradePassword(AES.AESEncode(Const.AceKey, memberPayPwd));
        //会员卡号生成
        member1.setCardNo(DateUtil.getMonth() + Tools.getRandomNum(6));
        try {
            //防止随便输入身份证号
            if (userAuthMessage.getIdNumber() != null && userAuthMessage.getIdNumber().length() == 18) {
                Integer sex = Integer.valueOf(userAuthMessage.getIdNumber().substring(16, 17));
                Byte memberSex = Byte.valueOf(Integer.valueOf(sex.intValue() % 2).toString());
                member1.setSex(Integer.valueOf(memberSex));
                member1.setIdNo(userAuthMessage.getIdNumber());
            } else {
                return message.format(false, -1, "身份证格式不正确", null);
            }
        } catch (Exception e) {
            return message.format(false, -1, "身份证格式不正确", null);
        }
            //插入会员表
            member1.setUserId(userId);
            int j = memberMapper.insertSelective(member1);
            if (j == 1) {
                    //更新虚拟卡号
                    String virtualCard = String.format("%s%s", payGroupCode, String.format("%011d", member1.getId()));
                    Member tempMember = new Member();
                    tempMember.setId(member1.getId());
                    tempMember.setVirtualCard(virtualCard);
                    memberMapper.updateByPrimaryKeySelective(tempMember);
                    //去支付平台开户
                    PayUserAccounts payUserAccounts = PayUserAccounts.initialize(payGroupCode,
                            virtualCard,
                            member1.getName(),
                            member1.getIdNo(),
                            memberPayPwd,
                            "000000",
                            "000000",
                            "000@163.com",
                            member1.getPhone(),
                            null,
                            DateUtils.getDateTimeString("yyyyMMddHHmmss"),null);
                    PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
                    if (payResult != null && payResult.getVerificationStatus().byteValue() == 1 && payResult.getRespCode().equals("0000")) {
                        /**
                         * 账户开设成功
                         */
                    	Token token=tokenService.getTokenInfo(member1.getId()+"");
                        member1.setMemberBalance(0.00);
                        member1.setMemberBalanceB(0.00);
                        member1.setNeedResetPwd(Byte.valueOf("1"));
                        return message.format(true, Integer.parseInt(member1.getId() + ""), "成功", member1,token.getValue());
                    
            } else {
                return message.format(false, -1, "系统配置错误", null);
            }
        } else {
            return message.format(false, -1, "系统配置错误", null);
        }
    }
    
    

    @Override
    public Response updatePayPwd(String groupId, UserAuthMessage userAuthMessage, String newPwd) {
        Response message = new Response();
        //判断是否注册钱包,这里将云流后台返回的userId当成微信的OpenId去查询会员信息
        Member member = memberMapper.selectYlUserId(userAuthMessage.getUserId()); //查询用户信息
        if (member == null) {
            return message.format(false, 0, "登录失效,请重新登录", null);
        } else {
            //根据钱包大机构号查询大商户ID
            Group group = groupMapper.selectGroupByPayCode(groupId);
            if (group == null || member == null || member.getGroupId() != group.getId()) {
                /**
                 * 会员不是当前商户的
                 */
                return message.format(false, -1, "非法操作", null);
            }
            //原始密码
            String mobilePhone = member.getPhone();
            String payPwd = UtilFun.creatDefaultPayPwd(mobilePhone);
            PayUpdatePayPwd upPayPwd = PayUpdatePayPwd.initialize(
                    member.getVirtualCard(),
                    payPwd,
                    newPwd,
                    groupId,
                    UtilFun.createRandomNum(10),
                    DateUtils.getDateTimeString("yyyyMMddHHmmss"),
                    UtilFun.createOrderNum());

            PayResult result = IPayAPI.updateAccountPayPwd(upPayPwd);
            if (result == null) {
                return message.format(false, 0, PayResult.getNotNullMsgTxt(result, "系统繁忙,修改密码失败"), null);
            }
            if (IPayAPI.Success.equals(result.getRespCode())) {
                try {
                    member.setTradePassword(AES.AESEncode(Const.AceKey, newPwd));
                    memberMapper.updateByPrimaryKeySelective(member);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return message.format(true, 0, "修改密码成功", null);
            }
            return message.format(false, 0, result.getMsgTxt(), null);
        }
    }

	@Override
	public boolean finishUpdateImg(String businessCode, String userId, String imgPath) {
		if(userId==null || businessCode==null||StringUtils.isBlank(imgPath)){
			return false;
		}
		//Group group=groupMapper.selectGroupByPayCode(businessCode);
		Member member =memberMapper.selectByThirdUserId(userId);
		if(member==null){
			return false;
		}
		member.setPicture(imgPath);
		int result=memberMapper.updateByPrimaryKeySelective(member);
		
		return result>=0;
	}


}
